//
//  AlbumViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-8.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "AlbumViewController.h"
#import "NetworkAccessManager.h"
#import <MMDrawerController/MMDrawerBarButtonItem.h>
#import <UIViewController+MMDrawerController.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <HFImageEditorViewController.h>
#import "UIAlertView+Kirinrin.h"
#import <UIProgressView+AFNetworking.h>
#import "SNSCropImageViewController.h"

#define kCropPhotoSize      320

@interface AlbumViewController ()
@property (strong, nonatomic)UIProgressView *uploadProgress;
@end

@implementation AlbumViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //configure the mwbrower
//    self.displayActionButton = YES; // Show action button to allow sharing, copying, etc (defaults to YES)

    
    
    
    self.appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    MMDrawerBarButtonItem *leftDrawerButton = [[MMDrawerBarButtonItem alloc]initWithTarget:self action:@selector(leftDrawerButtonPress:)];
    [self.navigationItem setLeftBarButtonItem:leftDrawerButton animated:YES];
    
    UIBarButtonItem *camera = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(beginCamera:)];
    self.navigationItem.rightBarButtonItem = camera;
    
    
    // Do any additional setup after loading the view.
//    [self loadRemoteData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)loadRemoteData{
    
    NSString *uriString = @"Photos.json";
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            self.remoteData = responseObject[@"data"];
//            self.startOnGrid = YES;
            [self reloadData];
//            [self setCurrentPhotoIndex:0];
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
    }];
    
}

-(void)leftDrawerButtonPress:(id)sender{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

//FIX: 上传的缩略图好像有点大
- (void)sendPhotoMessages:(UIImage *)photo preViewPhoto:(UIImage *)preViewPhoto{
    NSLog(@"sendPhotoMessages");
    NSString *uriString = @"Messages.json";
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey,};
    
    AFHTTPRequestOperation *uploadOpernation = [[NetworkAccessManager shareManager]POST:uriString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSData *photoData = UIImageJPEGRepresentation(photo, 0.4);
        NSData *preViewPhotoData = UIImageJPEGRepresentation(preViewPhoto, 0.8);
        
        [formData appendPartWithFileData:photoData name:@"photo" fileName:[NSString stringWithFormat: @"%@.jpg",[[NSProcessInfo processInfo]globallyUniqueString]] mimeType:@"image/jpeg"];
        [formData appendPartWithFileData:preViewPhotoData name:@"photoPre" fileName:[NSString stringWithFormat:@"%@.jpg",[[NSProcessInfo processInfo]globallyUniqueString]] mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            NSLog(@"图片上传成功!");
            
            [self.uploadProgress removeFromSuperview];
            self.uploadProgress = nil;
            
            [self loadRemoteData];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [self.uploadProgress removeFromSuperview];
        self.uploadProgress = nil;
        
//        [self loadRemoteData];
    }];
    
    // show progress view
    self.uploadProgress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    [self.view addSubview:self.uploadProgress];
    self.uploadProgress.center = self.view.center;
    [self.uploadProgress setProgressWithUploadProgressOfOperation:uploadOpernation animated:YES];
}

     
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)beginCamera:(UIBarButtonItem *)sender {
    NSLog(@"beginCamera");
    
    UIActionSheet *actionSheet;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
        NSString *destructiveButtonTitle = NSLocalizedString(@"拍照", nil);
        NSString *otherButtonTitle = NSLocalizedString(@"从相册中选取", nil);
        actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:otherButtonTitle, nil];
    }else{
        NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
        NSString *destructiveButtonTitle = NSLocalizedString(@"从相册中选取", nil);
        actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:nil, nil];
    }
    [actionSheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"button index %zd", buttonIndex);
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        if (buttonIndex == 0) {
            // 拍照
            
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:picker animated:YES completion:nil];
        }else if (buttonIndex == 1){
            // 从相册中选取
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }else{
        if (buttonIndex == 0) {
            // 从相册中选取
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
    
}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"pick a photo");
    //    UIImage *image =  [info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    
    
    [picker dismissViewControllerAnimated:NO completion:^{
        NSLog(@"dismissViewControllerAnimated imagePicker");
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            UIImage *preview = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
            
//            HFImageEditorViewController *imageEditor = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:kCropPhotoViewId];
            SNSCropImageViewController *imageEditor = [[SNSCropImageViewController alloc] initWithNibName:@"SNSCropImage" bundle:nil];
            imageEditor.cropRect = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.width);
            imageEditor.minimumScale = 0.2;
            imageEditor.maximumScale = 10;
            imageEditor.rotateEnabled = NO;
            
            imageEditor.sourceImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            imageEditor.previewImage = preview;
            
            imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
                NSLog(@"imageEditor.doneCallback");
                if (!canceled) {
                    //                    self.userPhoto = editedImage;
                    UIGraphicsBeginImageContext(CGSizeMake(kCropPhotoSize, kCropPhotoSize));
                    [editedImage drawInRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
                    UIImage *preViewPhoto = UIGraphicsGetImageFromCurrentImageContext();
                    UIGraphicsEndImageContext();
                    
                    [self sendPhotoMessages:editedImage preViewPhoto: preViewPhoto];
                }
                [self dismissViewControllerAnimated:NO completion:nil];
            };
            [self presentViewController:imageEditor animated:NO completion:nil];
        } failureBlock:^(NSError *error) {
            NSLog(@"error occour when read preview photo %@", error);
            
//            HFImageEditorViewController *imageEditor = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:kCropPhotoViewId];
            SNSCropImageViewController *imageEditor = [[SNSCropImageViewController alloc] initWithNibName:@"SNSCropImage" bundle:nil];
            imageEditor.cropRect = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.width);
            imageEditor.minimumScale = 0.2;
            imageEditor.maximumScale = 10;
            imageEditor.rotateEnabled = NO;
            
            imageEditor.sourceImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            //            imageEditor.previewImage = preview;
            
            imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
                NSLog(@"imageEditor.doneCallback");
                if (!canceled) {
                    //                    self.userPhoto = editedImage;
                    UIGraphicsBeginImageContext(CGSizeMake(kCropPhotoSize, kCropPhotoSize));
                    [editedImage drawInRect:CGRectMake(0, 0, kCropPhotoSize, kCropPhotoSize)];
                    UIImage *preViewPhoto = UIGraphicsGetImageFromCurrentImageContext();
                    UIGraphicsEndImageContext();
                    
                    [self sendPhotoMessages:editedImage preViewPhoto: preViewPhoto];
                }
                
                [self dismissViewControllerAnimated:NO completion:nil];
            };
            [self presentViewController:imageEditor animated:NO completion:nil];
        }];
        
        
    }];
    
}


#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser{
        return [self.remoteData count];
}
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{
//    NSDictionary *photoData = self.remoteData[index];
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:[self.remoteData[index]objectForKey:@"photoUrl"]]];
    photo.caption = @"照片";
    return photo;
}
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index{
    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:[self.remoteData[index]objectForKey:@"photoPreviewUrl"]]];
    photo.caption = @"照片";
    return photo;
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser{
    return;
}
@end
